package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    ServerSocket socket=null;
    public TcpEchoServer(int port) throws IOException {
        socket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
        Socket clientsocket= socket.accept();
        Thread t=new Thread(()->{
               processConnection(clientsocket);

       });
        t.start();

        }
    }

    private void processConnection(Socket clientsocket)  {
        //服务器启动
        System.out.printf("[%s:%d] 客户端上线\n",clientsocket.getInetAddress(),clientsocket.getPort());
            try (InputStream inputStream=clientsocket.getInputStream();
                 OutputStream outputStream=clientsocket.getOutputStream()) {
                //分析请求
                while (true) {
                    Scanner scanner = new Scanner(inputStream);
                    if (!scanner.hasNext()) {
                        System.out.printf("[%s:%d] 客户端下线\n", clientsocket.getInetAddress(), clientsocket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    //做出响应
                    String response = process(request);
                    //发送给客户端
                    PrintWriter writer = new PrintWriter(outputStream);
                    writer.println(response);
                    writer.flush();
                    //打印以下交互过程
                    System.out.printf("[%s:%d],req=%s,rep=%s\n", clientsocket.getInetAddress(), clientsocket.getPort(), request, response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    clientsocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer=new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
